package com.detech.sbom.business.user.serviceimpl;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.detech.sbom.base.config.mybatis.PageParam;
import com.detech.sbom.base.config.mybatis.SQLAdapter;
import com.detech.sbom.base.config.properties.HeadPictureProperties;
import com.detech.sbom.base.constant.Constants;
import com.detech.sbom.base.enumtype.MsgEnum;
import com.detech.sbom.base.exception.ServiceException;
import com.detech.sbom.base.mybatis.custom.user.CustomUserDao;
import com.detech.sbom.base.mybatis.login.dao.TbUserDao;
import com.detech.sbom.base.mybatis.login.entity.TbUserEntity;
import com.detech.sbom.base.satoken.enumtype.UserStatus;
import com.detech.sbom.base.satoken.properties.UserPasswordProperties;
import com.detech.sbom.base.util.UserFun;
import com.detech.sbom.business.login.service.LoginService;
import com.detech.sbom.business.user.model.UserOrderModel;
import com.detech.sbom.business.user.service.UserService;
import com.detech.sbom.business.user.sqlvo.UserListParam;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.StrUtil;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TbUserDao tbUserDao;
    @Resource
    private CustomUserDao customUserDao;
    @Autowired
    private HeadPictureProperties headPictureProperties;
    @Autowired
    private UserPasswordProperties userPasswordProperties;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Resource
    private LoginService loginService;

    @Override
    public void register(String username, String realname, int age) {
        // 注册用户信息
        TbUserEntity sysUser = new TbUserEntity();
        sysUser.setUsername(username);
        sysUser.setRealname(realname);
        sysUser.setAge(age);
        sysUser.setPassword(BCrypt.hashpw(userPasswordProperties.getDefaultPwd()));
        sysUser.setDelFlag(UserStatus.OK.getCode());
        sysUser.setStatus(UserStatus.OK.getCode());
        boolean exist = tbUserDao.exists(new LambdaQueryWrapper<TbUserEntity>().eq(TbUserEntity::getUsername, username));
        if (exist) {
            throw new ServiceException("注册失败，用户帐号【"+username+"】已经存在");
        }
        boolean regFlag = tbUserDao.insert(sysUser) > 0;
        if (regFlag) {
            loginService.recordLogininfor(username, Constants.REGISTER, MsgEnum.OPRATE_SUCCESS.getMsg(),null);
        }
    }

    @Override
    public boolean isUsernameExist(String username)  {
        TbUserEntity tbUserEntity = tbUserDao.selectOne(new LambdaQueryWrapper<TbUserEntity>(){{
            eq(TbUserEntity::getUsername,username);
        }});
        if(tbUserEntity!=null){
            return true;
        }
        return false;
    }

    @Override
    public TbUserEntity findUserById(String id)  {
        return tbUserDao.selectById(id);
    }

    @Override
    public void updateUser(TbUserEntity tbUserEntity)  {
        tbUserDao.updateById(tbUserEntity);
    }

    @Override
    public void uploadHeadPicture(String id,MultipartFile file) throws IOException {
        int index = file.getOriginalFilename().lastIndexOf(".");
        String newFileName = System.currentTimeMillis()+ UserFun.getRandomString(5)+file.getOriginalFilename().substring(index);//重新设置文件名
        String uploadFilePath = headPictureProperties.getFilePath();//得到上传文件主路径
        String filePath = uploadFilePath + newFileName;//得到文件的存储路径
        File newFile = new File(filePath);
        // 检测是否存在目录
        if (!newFile.getParentFile().exists()) {
            //不存在则创建目录
            newFile.getParentFile().mkdirs();
        }
        // 使用 spring 的 transferTo() 方法写入
        file.transferTo(newFile);

        TbUserEntity tbUserEntity = tbUserDao.selectById(id);
        tbUserEntity.setHeadPicture(newFileName);
        tbUserDao.updateById(tbUserEntity);
    }

    @Override
    public Page<TbUserEntity> loadUserList(PageParam pageParam, String username, String realname)  {
        LambdaQueryWrapper<TbUserEntity> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.like(StrUtil.isNotBlank(username),TbUserEntity::getUsername , username);
        userLambdaQueryWrapper.like(StrUtil.isNotBlank(realname),TbUserEntity::getRealname , realname);
        userLambdaQueryWrapper.orderByDesc(TbUserEntity::getAge);
        return tbUserDao.selectPage(pageParam.build() , userLambdaQueryWrapper);
    }

    @Override
    public Page loadUserOrderListMap(PageParam pageParam) {
        return customUserDao.loadUserOrderListMap(pageParam.build());
    }

    @Override
    public Page<UserOrderModel> loadUserOrderList(PageParam pageParam,String username,String realname)  {
        return customUserDao.loadUserOrderList(pageParam.build(),username,realname);
    }

    @Override
    public Page loadUserListMap(PageParam pageParam, String username, String realname)  {
        LambdaQueryWrapper<TbUserEntity> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.like(username!=null && username.trim().length()>0,TbUserEntity::getUsername , username);
        userLambdaQueryWrapper.like(realname!=null && realname.trim().length()>0,TbUserEntity::getRealname , realname);
        userLambdaQueryWrapper.orderByDesc(TbUserEntity::getAge);
        return tbUserDao.selectMapsPage(pageParam.build() , userLambdaQueryWrapper);
    }

    @Override
    public List<TbUserEntity> loadUserListNoPage(String username, String realname)  {
        LambdaQueryWrapper<TbUserEntity> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.like(username!=null && username.trim().length()>0,TbUserEntity::getUsername , username);
        userLambdaQueryWrapper.like(realname!=null && realname.trim().length()>0,TbUserEntity::getRealname , realname);
        userLambdaQueryWrapper.orderByDesc(TbUserEntity::getAge);
        return tbUserDao.selectList(userLambdaQueryWrapper);
    }

    @Override
    public List loadUserListMapNoPage(String username, String realname)  {
        LambdaQueryWrapper<TbUserEntity> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.select(TbUserEntity::getId,TbUserEntity::getUsername,TbUserEntity::getRealname,TbUserEntity::getAge);
        userLambdaQueryWrapper.like(username!=null && username.trim().length()>0,TbUserEntity::getUsername , username);
        userLambdaQueryWrapper.like(realname!=null && realname.trim().length()>0,TbUserEntity::getRealname , realname);
        userLambdaQueryWrapper.orderByDesc(TbUserEntity::getAge);
        return tbUserDao.selectMaps(userLambdaQueryWrapper);
    }

    @Override
    public List loadUserListSqlNoPageNoParam()  {
        String sql = "select * from tb_user t ";
        return sqlSessionTemplate.selectList("superSelect",new SQLAdapter(sql));
    }

    @Override
    public List loadUserListSqlNoPageParam(String username)  {
        String sql = "select * from tb_user t where t.username=#{username}";
        UserListParam param = new UserListParam(sql);
        param.setUsername(username);
        return sqlSessionTemplate.selectList("superSelect",param);
    }

    @Override
    public int deleteUserByIds(String[] userIds) {
        List<String> ids = Arrays.asList(userIds);
        return tbUserDao.deleteBatchIds(ids);
    }
}
